package lanbo.cj.lmp;

import android.app.Application;
import android.app.NotificationManager;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import cn.bmob.im.BmobChat;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.SaveListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.google.gson.Gson;
import lanbo.cj.lmp.utils.LocalData;
import lanbo.cj.lmp.utils.SharePreferenceUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class BaseApplication extends Application {

	public static BaseApplication mInstance;
	public LocationClient mLocationClient;
	public LocationClientOption mOption;
	public MyLocationListener mMyLocationListener;
	public String filePath = "";
	private Map<String, BmobChatUser> contactList = new HashMap<String, BmobChatUser>();

	public static BmobGeoPoint lastPoint = null;// 上一次定位到的经纬度
	public String mLocation;
	public double mLongitude;
	public double mLatitude;

	public static final String CACHE = "/sdcard/ihobby/Cache/";

	@Override
	public void onCreate() {
		super.onCreate();
		// 是否开启debug模式--默认开启状态
		BmobChat.DEBUG_MODE = true;
		mInstance = this;
		init();
	}

	private void init() {
		mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		initBaidu();
	}

	private void initBaidu() {
		// 初始化地图Sdk
		SDKInitializer.initialize(this);
		initLBS();
		// 初始化定位sdk
		initBaiduLocClient();
	}
	private void initLBS() {
		mOption = new LocationClientOption();
		mOption.setProdName("ihobby");// 设置产品线
		mOption.setOpenGps(true);// 打开gps
		mOption.setCoorType("bd09ll"); // 设置坐标类型
		mOption.setScanSpan(1000);
		mOption.setIsNeedAddress(true);
		mOption.setIgnoreKillProcess(true);
	}

	private void initBaiduLocClient() {
		mLocationClient = new LocationClient(this.getApplicationContext(),mOption);
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
	}

	/**
	 * 实现实位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			double latitude = location.getLatitude();
			double longtitude = location.getLongitude();
			mLocationClient.setDebug(true);

			if (lastPoint != null) {
				if (lastPoint.getLatitude() == location.getLatitude()
						&& lastPoint.getLongitude() == location.getLongitude()) {
					// BmobLog.i("两次获取坐标相同");// 若两次请求获取到的地理位置坐标是相同的，则不再定位
//					Toast.makeText(getApplicationContext(), "测试，纬度"+latitude, Toast.LENGTH_SHORT).show();
					mLatitude = latitude;
					mLongitude = longtitude;
					mLocationClient.stop();
					return;
				}
			}
			lastPoint = new BmobGeoPoint(longtitude, latitude);
		}


	}

	public static BaseApplication getInstance() {
		return mInstance;
	}

	// 单例模式，才能及时返回数据
	SharePreferenceUtil mSpUtil;
	public static final String PREFERENCE_NAME = "_sharedinfo";

	public synchronized SharePreferenceUtil getSpUtil() {
		if (mSpUtil == null) {
			String currentId = BmobUserManager.getInstance(getApplicationContext()).getCurrentUserObjectId();
			String sharedName = currentId + PREFERENCE_NAME;
			mSpUtil = new SharePreferenceUtil(this, sharedName);
		}
		return mSpUtil;
	}

	NotificationManager mNotificationManager;

	public NotificationManager getNotificationManager() {
		if (mNotificationManager == null)
			mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		return mNotificationManager;
	}


	public final String PREF_LONGTITUDE = "longtitude";// 经度
	private String longtitude = "";

	/**
	 * 获取经度
	 *
	 * @return
	 */
	public String getLongtitude() {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		longtitude = preferences.getString(PREF_LONGTITUDE, "");
		return longtitude;
	}

	/**
	 * 设置经度
	 *
	 * @param lon
	 */
	public void setLongtitude(String lon) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_LONGTITUDE, lon).commit()) {
			longtitude = lon;
		}
	}

	public final String PREF_LATITUDE = "latitude";// 经度
	private String latitude = "";

	/**
	 * 获取纬度
	 *
	 * @return
	 */
	public String getLatitude() {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		latitude = preferences.getString(PREF_LATITUDE, "");
		return latitude;
	}

	/**
	 * 设置维度
	 *
	 * @param lat
	 */
	public void setLatitude(String lat) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_LATITUDE, lat).commit()) {
			latitude = lat;
		}
	}

	/**
	 * 获取内存中好友user list
	 *
	 * @return
	 */
	public Map<String, BmobChatUser> getContactList() {
		return contactList;
	}

	/**
	 * 设置好友user list到内存中
	 *
	 * @param contactList
	 */
	public void setContactList(Map<String, BmobChatUser> contactList) {
		if (this.contactList != null) {
			this.contactList.clear();
		}
		this.contactList = contactList;
	}

	/**
	 * 退出登录,清空缓存数据
	 */
	public void logout() {
		BmobUserManager.getInstance(getApplicationContext()).logout();
		setContactList(null);
		setLatitude(null);
		setLongtitude(null);
	}

    /**
     * 往标签内写入
     * @param dataMap 写入的数据
     * @return boolean 是否写入成功
     * */
	public  boolean writeTag(Map dataMap,Tag tag){
        Gson gson = new Gson();
        String data = gson.toJson(dataMap);
        byte[] textBytes = data.getBytes();
        // image/jpeg text/plain
        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "image/jpeg".getBytes(), new byte[]{},
                textBytes);
        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{textRecord});
	    int size = ndefMessage.toByteArray().length;
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();

                if (!ndef.isWritable()) {
                    showToast("tag不允许写入");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    showToast("文件大小超出容量");
                    return false;
                }

                Log.i("nfc","写入成功");
                ndef.writeNdefMessage(ndefMessage);
                ndef.close();
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(ndefMessage);
                    } catch (IOException e) {
                        showToast("格式化tag失败.");
                        return false;
                    }
                } else {
                    showToast("Tag不支持NDEF");
                    return false;
                }
            }
        } catch (Exception e) {
            showToast("写入数据失败");
        }
        return false;
    }

    public void showToast(String msg){
        Toast.makeText(BaseApplication.getInstance(),msg,Toast.LENGTH_LONG).show();
    }
}
